package com.icecoding.linked_lists;

/**
 * 19.删除链表的倒数第N个节点
 */
public class removeNthFromEnd {
    public ListNode removeNthFromEndSolution(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        //删除倒数第n的节点,需要找到倒数第n+1的节点
        ListNode p = findLastNode(dummy, n + 1);
        p.next = p.next.next;
        return dummy.next;
    }

    public ListNode findLastNode(ListNode head, int n) {
        ListNode p1 = head;
        ListNode p2 = head;
        //p1先走n步
        for (int i = 0; i < n; i++) {
            p1 = p1.next;
        }
        //一起走,直到p1走到空节点位置, p1,p2走了 k - n 步, p2节点位于 k-n+1的位置,即倒数第n的位置
        while (p1 != null) {
            p1 = p1.next;
            //删除节点的上一个节点
            p2 = p2.next;
        }
        return p2;
    }

    public static void main(String[] args) {
        removeNthFromEnd removeNthFromEnd = new removeNthFromEnd();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        ListNode result = removeNthFromEnd.removeNthFromEndSolution(head, 2);
        while(result != null){
            System.out.println(result.val);
            result = result.next;
        }
    }
}

